package com.zh.web.aspect;

import com.zh.common.annotation.Operator;
import com.zh.common.dto.UserAuthDto;
import com.zh.common.properties.JwtProperties;
import com.zh.web.base.BaseController;
import com.zh.web.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;

@Aspect
@Component
@RequiredArgsConstructor
@Slf4j
@Order(1)
public class OperatorAspect {
    private final JwtUtil jwtUtil;
    private final JwtProperties jwtProperties;
    @Pointcut("@annotation(operator) || @within(operator)")
    public void annotatedWithOperator(Operator operator) {
    }
    /**
     * 记录操作人
     *
     * @param joinPoint
     * @param operator
     */
    @Before("annotatedWithOperator(operator)")
    public void authPoint(JoinPoint joinPoint, Operator operator) {
        Object target = joinPoint.getTarget();
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String authorization = request.getHeader(jwtProperties.getTokenName());
        if (target instanceof BaseController) {
            BaseController controller = (BaseController) target;
            if (jwtUtil.chickToken(authorization)) {
                UserAuthDto userAuthDto = jwtUtil.parseToken(authorization);
                controller.setOperator(userAuthDto.getId());
            } else {
                controller.setOperator(Long.parseLong(operator.value()));
            }
        }
    }
}